package com.xs.gis.cover.coverImpl;

import com.xs.gis.cover.FileCover;
import com.xs.gis.cover.SimpleCover;
import com.xs.gis.domain.geojson.GeoJsonFeature;
import com.xs.gis.util.JacksonUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.geotools.geojson.geom.GeometryJSON;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;

import java.io.*;

/**
 * @program: cdgis_geotoolsplus
 * @description:
 * @author: w
 * @create: 2023-08-18 09:26
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GeoJsonCover implements FileCover, SimpleCover {


    private int srid = 4490;

    @Override
    public Geometry dataToGeometry(String data) throws ParseException, IOException {
        Reader reader = new StringReader(data);
        GeometryJSON gjson = new GeometryJSON();
        Geometry geometry = gjson.read(reader);
        geometry.setSRID(srid);
        return geometry;
    }

    @Override
    public String geometryToData(Geometry geometry) throws UnsupportedEncodingException {
        GeometryJSON g = new GeometryJSON(15);
        return g.toString(geometry);
    }

    @Override
    public String featureToFile(GeoJsonFeature feature, String path) throws IOException {

        String jsonString = JacksonUtil.toJsonString(feature);
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(jsonString);
        bw.close();
        return jsonString;
    }

    /**
     * 文件路径解析为GeoJsonFeature对象
     *
     * @param filePath json
     * @return
     */
    @Override
    public GeoJsonFeature fileToFeature(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "GBK"));

        StringBuffer fileContent = new StringBuffer();
        // 逐行读取文件内容
        String line;
        while ((line = reader.readLine()) != null) {
            fileContent.append(line);
        }

        // 关闭 BufferedReader
        reader.close();
        return JacksonUtil.toObject(fileContent.toString(), GeoJsonFeature.class);
    }
}
